package com.ua.secure.user.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ua.common.model.PageResultBean;
import com.ua.common.model.SysOrg;
import com.ua.common.model.SysUser;
import com.ua.common.security.TissonDESPasswordEncoder;
import com.ua.open.common.service.CommonService;
import com.ua.secure.org.service.OrgService;
import com.ua.secure.user.service.UserService;

/**
 * 用户管理配置控制器
 * @author yangying
 * 2013-4-9
 */
@Controller
@RequestMapping("/secure/user/*")
public class UserController {

	
	@Autowired(required=true)
	private OrgService orgService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private CommonService commonService;

	@RequestMapping(value="initUser.html")
	public ModelAndView initUser(){
		ModelAndView mav = new ModelAndView();
		mav.addObject("addUser",new SysUser());
		mav.setViewName("secure/user/addUserForm");
		return mav;
	}
	
	@RequestMapping("listUsers.html")
	public ModelAndView listUsers() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("org",orgService.queryOrgByOrgId("1"));
		mav.addObject("user",new SysUser());
		mav.setViewName("secure/user/queryUser");
		return mav;
	}
	
	@RequestMapping("loadUserOrgsData.html")
	public @ResponseBody List<SysOrg> loadUserOrgsData(){
		List<SysOrg> list = orgService.loadOrgsData();
		// 去掉parentSysOrg
		for(SysOrg m : list){
			m.setParentSysOrg(null);
		}
		return list;
	}
	
	@RequestMapping("queryUserOrgByOrgId.html")
	public ModelAndView queryOrgByOrgId(@RequestParam String orgId) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("org", orgService.queryOrgByOrgId(orgId));
		mav.setViewName("secure/user/queryUser");
		return mav;
	}	
	
	@RequestMapping(value="loadAllUsers.html")
	public @ResponseBody PageResultBean loadAllUsers(Integer jtStartIndex,Integer jtPageSize,String orgId,String userName,String loginName){
		PageResultBean pr = new PageResultBean();
		try {
			SysUser user = new SysUser();
			user.setOrgId(orgId);
			user.setUserName(userName);
			user.setLoginName(loginName);
			user.setFromNumber(jtStartIndex);
			user.setToNumber(jtStartIndex+jtPageSize);
			pr.setResult("OK");
			pr.setRecords(userService.queryAllUsers(user));
			pr.setTotalRecordCount(userService.userCount(user));
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
		}
		
		return pr;
	}
	//保存
	@RequestMapping(value="saveUser.html")
	public @ResponseBody PageResultBean saveUser(SysUser user,String orgIds,String resTreeIds){
		PageResultBean pr = new PageResultBean();
		try {
			if(user!=null){
				String userId = user.getUserId();
				if(userId!=null && !"".equals(userId)){
					user.setUpdateDate(commonService.getDatabaseCurrentTime());
					user.setRoleId("");
					userService.updateUser(user);
				}else{
					user.setUserId(commonService.getCode());
					user.setCreateDate(commonService.getDatabaseCurrentTime());
					user.setIsValid("Y");
					user.setRoleId("");
					if(user.getPassword() != null && !"".equals(user.getPassword().trim())){
						TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
						user.setPassword(pwdEncoder.encodePassword(user.getPassword(), ""));
					}else{
						user.setPassword("1111");
						TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
						user.setPassword(pwdEncoder.encodePassword(user.getPassword(), ""));
					}
					
					userService.saveUser(user);
				}
			}
			pr.setResult("OK");
			pr.setRecord(user);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
			pr.setMessage("保存失败!");
		}
		return pr;
	}
	
	@RequestMapping(value="updateUser.html")
	public ModelAndView updateUser(String userId){
		ModelAndView mav = new ModelAndView();
		try{
			SysUser user = userService.queryUserByUserId(userId);
			mav.addObject("addUser",user);
			
			mav.setViewName("secure/user/addUserForm");
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return mav;
	}
	
	/**
	 * 初始化修改密码界面
	 * @return
	 */
	@RequestMapping(value="initPw.html")
	public ModelAndView init(String userId){
		ModelAndView mav = new ModelAndView();
		mav.addObject("pwModel",userService.queryUserByUserId(userId));
		mav.setViewName("secure/user/updatePw");
		return mav;
	}
	
	/**
	 * 修改用户密码
	 * @param user
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="updatePw.html")
	public @ResponseBody Map<String,Object> save(SysUser user) throws IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			if(user!=null){
				String userId = user.getUserId();
				String selfPassword = user.getSelfPassword();
				String oldPassword = user.getPassword();
				if(userId!=null && !"".equals(userId)){
					TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
					selfPassword = pwdEncoder.encodePassword(selfPassword, "");
					if(selfPassword.equals(oldPassword)){
						String pwString = pwdEncoder.encodePassword(user.getNewPassword(), "");
						user.setPassword(pwString);
						userService.updatePw(user);
						map.put("flag", "ok");
					}else{
						map.put("flag", "fail");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("flag", "error");
		}
		return map;
	}

	//批量删除
	@RequestMapping(value="delUser.html")
	public @ResponseBody PageResultBean delete(String userIds){
		PageResultBean pr = new PageResultBean();
		try {
			if(userIds != null && !"".equals(userIds)){
				String[] userId = userIds.split(",");
				for (String s : userId) {
					userService.delUser(s);
					pr.setResult("OK");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
			pr.setMessage("删除失败!");
		}
		return pr;
	}
	
	//批量重置密码
	@RequestMapping(value="resetPassword.html")
	public @ResponseBody PageResultBean resetPassword(String userIds){
		PageResultBean pr = new PageResultBean();
		try {
			if(userIds != null && !"".equals(userIds)){
				String[] userId = userIds.split(",");
				
				for (String s : userId) {
					SysUser user = userService.queryUserByUserId(s);
					user.setPassword("1111");
					TissonDESPasswordEncoder pwdEncoder = new TissonDESPasswordEncoder();
					user.setPassword(pwdEncoder.encodePassword(user.getPassword(), ""));
					userService.resetPassword(user);
					pr.setResult("OK");
				}	
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			pr.setResult("ERROR");
			pr.setMessage("重置密码失败!");
		}
		return pr;
	}
}
